package com.heima.article.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.heima.article.entity.ApAuthor;
import com.heima.article.mapper.ApAuthorMapper;
import com.heima.article.service.ApAuthorService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.exception.LeadException;
import com.heima.common.util.BeanHelper;
import com.heima.model.article.dtos.AuthorDto;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * <p>
 * APP文章作者信息表 服务实现类
 * </p>
 *
 * @author HM
 * @since 2023-05-25
 */
@Service
public class ApAuthorServiceImpl extends ServiceImpl<ApAuthorMapper, ApAuthor> implements ApAuthorService {

    /**
     * 保存文章作者
     * @param dto
     * @return
     */
    /*@Override
    public Integer saveAuthor(AuthorDto dto) {
//        先根据userId查询作者
        LambdaQueryWrapper<ApAuthor> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ApAuthor::getUserId,dto.getUserId());
        ApAuthor apAuthor = getOne(queryWrapper);
//        如果没有数据，新增
        if(apAuthor == null){
            apAuthor = new ApAuthor();
            apAuthor.setUserId(dto.getUserId());
            apAuthor.setWmUserId(dto.getWmUserId());
            apAuthor.setCreatedTime(new Date());
            apAuthor.setType(dto.getType());
        }
        apAuthor.setName(dto.getName());
//        新增或修改数据
        boolean b = saveOrUpdate(apAuthor);
        if(!b){
            log.error("保存文章作者失败！");
            throw new LeadException(AppHttpCodeEnum.SAVE_AP_AUTHOR_ERROR);
        }
        return apAuthor.getId();
    }*/

    @Override
    public Integer saveAuthor(AuthorDto dto) {
        // 先根据WmUserId查询作者，如果有就更新，没有就插入
        LambdaQueryWrapper<ApAuthor> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ApAuthor::getWmUserId, dto.getWmUserId());
        ApAuthor authorDB = this.getOne(queryWrapper);
        if(authorDB == null){
            // insert
            ApAuthor insertAuthor = buildInsertAuthor(dto);
            this.save(insertAuthor);
            return insertAuthor.getId();
        }else{
            // update
            ApAuthor updateAuthor = buildUpdateAuthor(authorDB, dto);
            this.updateById(updateAuthor);
            return updateAuthor.getId();
        }
    }

    private ApAuthor buildInsertAuthor(AuthorDto dto) {
        ApAuthor author = BeanHelper.copyProperties(dto, ApAuthor.class);
        author.setCreatedTime(new Date());
        return author;
    }


    private ApAuthor buildUpdateAuthor(ApAuthor authorDB, AuthorDto dto) {
        ApAuthor author = BeanHelper.copyProperties(dto, ApAuthor.class);
        author.setId(authorDB.getId());
        author.setWmUserId(null);
        return author;
    }
}
